package com.baizhi.aspect;

import com.baizhi.annotation.AddLog;
import com.baizhi.entity.Admin;
import com.baizhi.entity.Log;
import com.baizhi.service.LogService;
import com.baizhi.util.UUIDUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.lang.reflect.Method;
import java.util.Date;

@Configuration  //配置类  交给工厂管管理
@Aspect //该类是一个切面类
public class LogAspect {
    private static final Logger log1 = LoggerFactory.getLogger(LogAspect.class);
    @Resource
    HttpServletRequest request;

    @Resource
    LogService logService;


    @Around("@annotation(com.baizhi.annotation.AddLog)")
    public Object AddLog(ProceedingJoinPoint proceedingJoinPoint){

        System.out.println("------------------进入环绕通知------------------");

        //获取用户
        Admin admin =(Admin) request.getServletContext().getAttribute("admin");

        //获取操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取方法
        Method method = signature.getMethod();
        //获取方法的注解
        AddLog addLog = method.getAnnotation(AddLog.class);
        //获取注解上的属性值
        String value = addLog.value();

        String status= null;
        Object result = null;
        try {
            //放行通知执行目标方法
            result = proceedingJoinPoint.proceed();
            status="Success(执行成功)";
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            status="Error(执行失败)";
        }
        Log log = new Log(null, admin.getUsername(), new Date(), methodName+"("+value+")", status);
        log1.info("进入日志:{}",log);
        //日志信息入库
        logService.add(log);
        return result;
    }
}
